<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-shop"></i>
          养生分类
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-input
          v-model="searchName"
          placeholder="分类名称"
          class="handle-input mr10"
          width="55"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch"
          >搜索</el-button
        >
        <el-button type="primary" icon="el-icon-lx-friendadd" @click="showBox()"
          >添加分类</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <el-table-column prop="name" label="分类名称"></el-table-column>
        <el-table-column prop="classifyPic" label="分类图标">
          <template #default="scope">
            <el-image
              class="table-td-thumb"
              :src="scope.row.iconUrl"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="classifySort" label="排序字段"></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          :formatter="dateFormat"
        ></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="创建用户" v-model="showAddUser" width="50%">
      <el-form
        ref="form"
        :model="classlist"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="classlist.name"
            placeholder="请输入分类名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="父级分类ID" prop="parentId">
          <el-input-number
            v-model="classlist.parentId"
            :min="0"
            placeholder="0为顶级分类"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="分类图标">
          <div class="crop-demo">
            <img
              v-if="classlist.iconUrl"
              :src="classlist.iconUrl"
              class="pre-img"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="image/*"
              @change="setImage"
            />
          </div>
        </el-form-item>
        <el-form-item label="排序字段" prop="sortOrder">
          <el-input-number
            v-model="classlist.sortOrder"
            :min="0"
            placeholder="数值越小越靠前"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="是否在搜索展示" prop="showInSearch">
          <el-radio-group v-model="classlist.showInSearch">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input-number
            v-model="classlist.status"
            :min="0"
            placeholder="请输入状态值"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddUser = false">取 消</el-button>
          <el-button v-if="isChange == 1" type="primary" @click="addClass"
            >确 定</el-button
          >
          <el-button v-else type="primary" @click="editClass">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { upload, api } from "../../api/index";
import { formatDate } from "@/common/data";
import moment from "moment";

export default {
  inject: ["reload"],
  filters: {
    formatDate(time) {
      time = time * 1000;
      let date = new Date(time);
      console.log(new Date(time));
      return formatDate(date, "yyyy-MM-dd hh:mm");
    },
  },
  name: "basetable",
  data() {
    return {
      query: {
        pageNo: 1,
      },
      searchName: "",
      tableData: [],
      // multipleSelection: [],
      showAddUser: false,
      pageTotal: 0,
      classlist: {
        name: "",
        parentId: 0,
        iconUrl: "",
        sortOrder: 1,
        showInSearch: 1,
        status: 1,
        classifyPic: "1",
      },
      classSonList: {},
      isChange: "",
      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "分类名称长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        parentId: [
          { required: true, message: "请输入父级分类ID", trigger: "blur" },
          { type: "number", message: "父级分类ID必须为数字" },
        ],
        iconUrl: [
          { required: true, message: "请输入图标URL", trigger: "blur" },
        ],
        sortOrder: [
          { required: true, message: "请输入排序字段", trigger: "blur" },
          { type: "number", message: "排序字段必须为数字" },
        ],
        showInSearch: [
          {
            required: true,
            message: "请选择是否在搜索展示",
            trigger: "change",
          },
        ],
        status: [
          { required: true, message: "请输入状态", trigger: "blur" },
          { type: "number", message: "状态必须为数字" },
        ],
      },
    };
  },
  created() {
    this.getData();
  },
  mounted() {},
  methods: {
    dateFormat: function (row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    joinpic(item) {
      return `https://www.yaozhuasocial.com/imgs/${item}`;
    },
    // 获取分类列表
    getData() {
      api("/web/wellness/category/g", {
        limit: 10,
        offset: this.query.pageNo,
        parentId: 0,
      }).then((res) => {
        // console.log(res.data);
        this.tableData = res.data.rows;
        this.pageTotal = res.data.total;
      });
    },

    //上传图片
    setImage(file) {
      let imgFile = file.target.files[0];
      let formData = new FormData();
      formData.append("file", imgFile);
      upload(formData).then((res) => {
        this.classlist.iconUrl = res.data;
      });
    },

    //显示编辑框
    showBox() {
      this.showAddUser = true;
      this.isChange = 1;
      // 重置表单
      this.classlist = {
        name: "",
        parentId: 0,
        iconUrl: "",
        sortOrder: 1,
        showInSearch: 1,
        status: 1,
        classifyPic: "1",
      };
    },

    //创建分类
    addClass() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.showAddUser = false;
          api("/web/wellness/category/a", this.classlist).then((res) => {
            if (res.code === 2000) {
              this.$message.success("新增分类成功");
              this.classlist = {
                name: "",
                parentId: 0,
                iconUrl: "",
                sortOrder: 1,
                showInSearch: 1,
                status: 1,
                classifyPic: "1",
              };
              this.reload();
            } else {
              this.$message.error(res.message);
            }
          });
        } else {
          this.$message.error("请填写完整的表单信息");
        }
      });
    },

    // 触发搜索按钮
    handleSearch() {
      this.getData();
    },

    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      let data = JSON.parse(JSON.stringify(row));
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          api("/web/wellness/category/d", {
            id: data.id,
          }).then((res) => {
            if (res.code === 2000) {
              this.$message.success(res.message);
              this.reload();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {});
    },
    // 编辑操作
    handleEdit(index, row) {
      this.showAddUser = true;
      this.isChange = 0;
      let data = JSON.parse(JSON.stringify(row));
      this.classlist = {
        name: data.name || data.classifyName || "",
        parentId: data.parentId || 0,
        iconUrl: data.iconUrl || "",
        sortOrder: data.sortOrder || data.classifySort || 1,
        showInSearch: data.showInSearch !== undefined ? data.showInSearch : 1,
        status: data.status !== undefined ? data.status : 1,
        classifyPic: data.classifyPic || data.classifyLogo || "1",
        id: data.id,
      };
    },
    //修改分类
    editClass() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.showAddUser = false;
          api("/web/wellness/category/u", this.classlist).then((res) => {
            if (res.code === 2000) {
              this.$message.success("修改分类成功");
              this.classlist = {
                name: "",
                parentId: 0,
                iconUrl: "",
                sortOrder: 1,
                showInSearch: 1,
                status: 1,
                classifyPic: "1",
              };
              this.reload();
            } else {
              this.$message.error(res.message);
            }
          });
        } else {
          this.$message.error("请填写完整的表单信息");
        }
      });
    },
    // 分页导航
    handlePageChange(val) {
      // console.log(val);
      this.query.pageNo = val;
      this.getData();
    },
  },
};
</script>

<style lang="scss" scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

.crop-demo {
  display: flex;
  align-items: flex-end;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 178px;
  height: 178px;

  .pre-img {
    width: 178px;
    height: 178px;
    background: #f8f8f8;
    border: 1px solid #eee;
    border-radius: 5px;
    object-fit: cover;
  }

  .crop-input {
    position: absolute;
    width: 178px;
    height: 178px;
    left: 0px;
    top: 0px;
    opacity: 0;
    cursor: pointer;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
}
</style>
